package com.wangp.mywrite.s_juc.cas;

/**
 * @author farling-wangp
 * @version 1.0
 * @date 2020/10/11 20:09
 */
public class TwoThreadCompetition implements Runnable{
    private volatile int value;

    public synchronized int compareAndSwap(int expectedValue, int newValue) {
        int oldValue = value;
        if (oldValue == expectedValue) {
            value = newValue;
        }
        return oldValue;
    }

    public static void main(String[] args) throws InterruptedException {
        TwoThreadCompetition r = new TwoThreadCompetition();
        r.value = 0;
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(r.value);
    }
    @Override
    public void run() {
        compareAndSwap(0,1);
    }
}
